import re
import os


def inline_html(ts_file):
    """内置HTML模板"""
    html_file = get_html_file(ts_file)
    if not os.path.exists(html_file):
        print("没有外置的HTML文件: " + html_file)
        return

    with open(html_file, "r", encoding="utf-8") as f:
        html = f.read()
    with open(ts_file, "r", encoding="utf-8") as f:
        content = f.read()
    pattern = r"templateUrl\s*:\s*'[^']+'"
    if not re.search(pattern, content):
        print("没有templateUrl")
        return
    replacement = f"template: `{html}`"
    new_content = re.sub(pattern, replacement, content)
    with open(ts_file, "w", encoding="utf-8") as f:
        f.write(new_content)
    os.remove(html_file)


def outline_html(ts_file):
    """外置模板"""
    with open(ts_file, "r", encoding="utf-8") as f:
        content = f.read()
    pattern = re.compile(r"template\s*:\s*`([^`]+)`", re.DOTALL)
    match = re.search(pattern, content)

    if not match:
        return

    html = match.group(1)
    if html:
        html_file = get_html_file(ts_file)
        html_filename = os.path.basename(html_file)
        with open(html_file, "w", encoding="utf-8") as f:
            f.write(html)
        ref = f"templateUrl: './{html_filename}'"
        content = re.sub(pattern, ref, content)
        with open(ts_file, "w", encoding="utf-8") as f:
            f.write(content)
    else:
        print("不存在内嵌HTML模板")


def get_html_file(ts_file):
    """取得对应的HTML文件"""
    return ts_file.replace(".ts", ".html")


def inline_less(ts_file):
    """内置less"""
    less_file = ts_file.replace(".ts", ".less")
    if not os.path.exists(less_file):
        return

    with open(less_file, "r", encoding="utf-8") as f:
        less = f.read()
    with open(ts_file, "r", encoding="utf-8") as f:
        content = f.read()
    pattern = r"styleUrl\s*:\s*'[^']+'"
    if not re.search(pattern, content):
        print("没有styleUrl")
        return
    replacement = f"styles: `{less}`"
    new_content = re.sub(pattern, replacement, content)
    with open(ts_file, "w", encoding="utf-8") as f:
        f.write(new_content)
    os.remove(less_file)


def outline_less(ts_file):
    """外置less"""
    with open(ts_file, "r", encoding="utf-8") as f:
        content = f.read()
    pattern = re.compile(r"styles\s*:\s*`([^`]+)`", re.DOTALL)
    match = re.search(pattern, content)

    if not match:
        return

    css = match.group(1)
    less_file = get_less_file(ts_file)
    less_file_name = os.path.basename(less_file)
    with open(less_file, "w", encoding="utf-8") as f:
        f.write(css)
    ref = f"styleUrl: './{less_file_name}'"
    content = re.sub(pattern, ref, content)
    with open(ts_file, "w", encoding="utf-8") as f:
        f.write(content)


def get_less_file(ts_file):
    """取得对应的less文件"""
    return ts_file.replace(".ts", ".less")
